<template></template>
<script>
// #ifdef H5
import { mapActions, mapState } from 'vuex';
import { uniLinkTo } from '@/utils/uniPromise';

export default {
	data() {
		return {
			step: 0
		};
	},
	computed: {
		...mapState(['vuex_login_back_url'])
	},
	async mounted() {
		this.$loading('正在登录');
		if(process.env.NODE_ENV === 'production'){
			this.pageInit()
		}else{
			// 59 1000120 1000163
			this.loadUserInfo({dev:true,users_id:1419185}).then(()=>{
				this.$hide()
				uniLinkTo('/pages/index/index', 'switchTab')
			}).catch(()=>{this.$hide()})
		}
		
	},
	methods: {
		...mapActions(['loadUserOpenid', 'loadUserInfo','checkIsUpdateSuperior']),
		// https://developers.weixin.qq.com/doc/offiaccount/OA_Web_Apps/Wechat_webpage_authorization.html
		pageInit () {
			let code = this.$route.query.code;
			if (code) {
				// 携带code
				this.getUserInfo(code);
			} else {
				this.$hide();
				let appId = this.vuex_business.appid;
				let redirectUrl = window.location.origin + `/package/common/auth/index`;
				redirectUrl = encodeURIComponent(redirectUrl);
				let url = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appId}&redirect_uri=${redirectUrl}&response_type=code&scope=snsapi_userinfo&state=wxLoginBack#wechat_redirect`;
				window.location.replace(url);
			}
		},
		getUserInfo(code) {
			// 获取用户openid
			this.loadUserOpenid({
				code
			})
				.then(() => {
					this.loadUserInfo().then(() => {
							this.$hide();
							if (!this.vuex_login_back_url || this.vuex_login_back_url.includes('package/common/auth') || this.vuex_login_back_url === '/') {
								uniLinkTo('/pages/index/index', 'switchTab');
							} else {
								this.handSuperior()
								uniLinkTo(this.vuex_login_back_url);
								this.$u.vuex('vuex_login_back_url', '');
							}
						})
						.catch(err => {
							console.error(err);
							this.$hide();
							this.$toast(err);
						});
				})
				.catch(err => {
					console.error(err);
					this.$hide();
					this.$toast(err);
				});
		},
		// 处理分享用户id
		handSuperior () {
			let str = this.vuex_login_back_url.split('?')[1] || ''
			if(str && str.includes('superior')){
				let arr = str.split('&')
				arr.some((arrStr)=>{
					if(arrStr.includes('superior')){
						let superiorId = arrStr.split('=')[1]
						this.checkIsUpdateSuperior(superiorId)
						return true	
					}else{
						return false
					}
				})
			}
		}
	}
};
// #endif
</script>
